<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '登录',
    navigationStyle: 'custom',
  },
}
</route>
<template>
  <view style="position: relative; height: 100vh">
    <view class="bgContainer">
      <view class="bg-wrapper">
        <image class="bgImage" :src="backgroundImage" mode="widthFix" />
        <image class="bgColor" :src="appBackgroundColor" mode="widthFix" />
        <image class="bgLogo" :src="appLogo" mode="widthFix" />
        <view class="bgTextZH">我对代表说句话</view>
        <view class="bgTextTibetan" v-if="showTibetan">བོད་ཀྱི་སྐདབོད་ཀྱི་སྐདབོད་ཀྱི་སྐད</view>
      </view>
    </view>
    <!-- <Verify @success="pwdLogin" :mode="'pop'" :captchaType="'blockPuzzle'"
			:imgSize="{ width: '330px', height: '155px' }" ref="verify"></Verify> -->
    <view class="mt-4">
      <view class="form-card">
        <wd-form ref="formRef" :model="loginForm" :rules="formRules">
          <wd-cell-group>
            <view class="form-border">
              <wd-input
                prefix-icon="user"
                center
                size="large"
                prop="username"
                v-model="loginForm.username"
                :placeholder="showTibetan ? '请输入账号(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)' : '请输入账号'"
                no-border
              />
            </view>
            <view class="form-border">
              <wd-input
                prefix-icon="lock-on"
                size="large"
                prop="password"
                show-password
                v-model="loginForm.password"
                :placeholder="showTibetan ? '请输入密码(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)' : '请输入密码'"
                no-border
              />
            </view>
          </wd-cell-group>
        </wd-form>
        <!-- <view class="form-register">
					还没有账号？
					<text @click="toRegister">立即注册 </text>
					<text style="color: #ccc;margin-left: 25%;" @click="resetPassword">忘记密码</text>
				</view> -->
        <view class="mt-8 btn-wrapper">
          <wd-button
            type="error"
            size="large"
            @click="handleLogin"
            custom-class="custom-shadow"
            customStyle=" width: 60vw;
						 height: 5vh "
          >
            <view class="zh-tb-text text-#fff">
              <text>登录</text>
              <text style="color: #fff">བོད་ཀྱི་སྐད་</text>
            </view>
          </wd-button>
          <!-- <wd-button type="error" size="large" @click="handleLoginFace" block>人脸</wd-button> -->
          <!-- <wd-button type="error" size="large" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"
            block>手机登录</wd-button> -->
          <!-- <view style="text-align: center;margin-top: 20rpx; color: red;font-size: 14px;">
						忘记密码
					</view> -->
        </view>
        <view class="mt-8 flex justify-between">
          <view
            class="flex flex-col items-center justify-center leading-[1.2] border border-#ffd2a5 bg-[#ffeedd] text-red p-2"
            @click="resetPassword"
          >
            <view>忘记密码</view>
            <view v-if="showTibetan">བོད་ཀྱི་སྐད་</view>
          </view>
          <view
            class="flex flex-col items-center justify-center leading-[1.2] border border-#ffd2a5 bg-[#ffeedd] text-red p-2"
            @click="toRegister"
          >
            <view>
              <span class="text-#000">还没账号，立即</span>
              注册
            </view>
            <view v-if="showTibetan">བོད་ཀྱི་སྐད་</view>
          </view>
        </view>
        <!-- <view class="mt-6 text-center">
          <text class="text-grey1">登录即代表同意</text>
          <text class="text-black" @click="goToUserAgreement">《用户协议》</text>
          <text class="text-black" @click="goToPrivacyPolicy">《隐私政策》</text>
        </view> -->
        <view class="agreement px-4 py-8">
          <checkbox class="checkbox" :checked="agreed" @click="toggleAgreement" />
          <text class="agreement-text">我已认真阅读留言须知。查看</text>
          <text class="link" @click="goToUserAgreement">《用户服务协议》</text>
          <text class="agreement-text">及</text>
          <text class="link" @click="goToPrivacyPolicy">《个人信息保护政策》</text>
        </view>
        <view class="text-center" v-if="showTibetan">
          བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་
        </view>
      </view>
    </view>
    <CaptchaPopup ref="captchaRef" @success="onCaptchaSuccess" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import Verify from '@/components/verifition/index.vue'
import CaptchaPopup from './CaptchaPopup.vue'

import { useUserStore } from '@/store/user'
import { getCode, getTenantInfo } from '@/api/login'
import { useTenantStore } from '@/store/tenant'

// import { useDictStoreWithOut } from '@/store/modules/dict'
const store = useUserStore() // 获取 Vuex store
const tenantStore = useTenantStore()

const defaultBackground = import.meta.env.VITE_APP_BG_GH3 || '/static/bgGH3.jpg'
const tenant = computed(() => tenantStore.tenantInfo)
const backgroundImage = computed(() =>
  showTibetan ? appBackgroundXH : tenant.value.logoUrl || defaultBackground,
)

// const dictStore = useDictStoreWithOut()

const captchaRef = ref()
// 获取环境变量
const showTibetan = import.meta.env.VITE_SHOW_TIBETAN === 'true'
const appTitle = ref(import.meta.env.VITE_APP_TITLE || 'Unibest Login')
const appLogo = ref(import.meta.env.VITE_APP_LOGO || '/static/logo.png')
const appBackgroundXH = ref(import.meta.env.VITE_APP_BG_XH || '/static/bgXH.png')

const appBackgroundGH = ref(import.meta.env.VITE_APP_BG_GH1 || '/static/bgGH1.png')
// const appBackgroundGH = ref(import.meta.env.VITE_APP_BG_GH2 || '/static/bgGH2.jpg')
// const appBackgroundGH = ref(import.meta.env.VITE_APP_BG_GH3 || '/static/bgGH3.jpg')

const appBackgroundColor = ref(import.meta.env.VITE_APP_LOGO || '/static/bgcolor.png')

const verify = ref()
const captchaEnabled = ref(true)

const agreed = ref(false)
const formRef = ref()
const loginForm = ref({
  username: '',
  password: '',
  code: '', // 用户输入的验证码内容
  uuid: '', // 后端返回的验证码唯一标识
  tenantId: undefined,
  // captchaVerification: ""
})
const formRules: any = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: ['blur', 'change'],
    },
    {
      validator: (value: any) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('用户名不能为空')
        }
      },
      trigger: ['blur'], // validator 也建议加 trigger
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: ['blur', 'change'],
    },
    // 正则判断为字母或数字
    // {
    //   pattern: /^[0-9a-zA-Z]*$/g,
    //   // 正则检验前先将值转为字符串
    //   transform(value: any) {
    //     return String(value)
    //   },
    //   message: '只能包含字母或数字',
    // },
    {
      validator: (value: any) => {
        if (value.length >= 5 && value.length <= 12) {
          return Promise.resolve()
        } else {
          return Promise.reject('密码长度必须在5到12位之间')
        }
      },
      trigger: 'blur',
    },
  ],
}
const toggleAgreement = () => {
  agreed.value = !agreed.value
}
const toRegister = () => {
  console.log('点击了')
  uni.navigateTo({ url: `/pages/register/index` })
}
const resetPassword = () => {
  console.log('修改密码')
  uni.navigateTo({ url: `/pages/forgetPassword/index` })
}
/**用户协议*/
const goToUserAgreement = () => {
  uni.navigateTo({ url: '/pages/agreement/user/index' })
}
/**隐私政策*/
const goToPrivacyPolicy = () => {
  uni.navigateTo({ url: '/pages/agreement/privacy/index' })
}

const pages = getCurrentPages()
const onGetPhoneNumber = async (e: any) => {
  console.log('e', e)

  console.log('pages', pages)

  if (!e.errMsg?.endsWith('ok')) {
    // 用户取消授权

    console.log('取消了授权')

    return
  }

  // const res = await postLoginWxMinAPI({

  // 	code,

  // 	encryptedData: e.encryptedData,

  // 	iv: e.iv,

  // })

  // useMember.setProfile(res.data)

  // 1.提示用户登录成功

  uni.showToast({
    title: '登录成功',

    icon: 'success',
  })

  setTimeout(() => {
    uni.switchTab({
      url: `/pages/index/index`,
    })
  }, 1000)
}
const handleLoginFace = () => {
  uni.startFacialRecognitionVerify({
    certifyId: '',
    progressBarColor: '#CC0000', //刷脸圈的颜色
    screenOrientation: 'port', //认证界面UI朝向
    success: (e) => {
      console.log(JSON.stringify(e))
    },
    fail: (e) => {
      console.log(JSON.stringify(e))
    },
    complete: (e) => {
      console.log(JSON.stringify(e))
    },
  })
}
const handleLogin = async () => {
  if (!agreed.value) {
    uni.showToast({
      title: '请先阅读并同意协议',
      icon: 'none',
    })
    return
  }
  // 校验表单
  if (!formRef.value) return
  // const valid = await formRef.value.validate();
  // console.log('valid', valid);
  const { valid, errors } = await formRef.value.validate()
  if (!valid) {
    console.log('表单校验未通过:', errors)
    return // ✅ 校验失败，终止后续代码
  }

  // if (captchaEnabled.value && verify.value) {
  // 	verify.value.show();
  // } else {
  // 	console.log('没进来');
  // 	await pwdLogin({});
  // }
  const res = await getCode()
  const imageBase64 = res.data?.img
  const uuid = res.data?.uuid
  console.log('uuid', uuid)

  // 弹出验证码弹窗
  if (captchaRef.value) {
    console.log('进来了吗')
    captchaRef.value.open('data:image/png;base64,' + imageBase64, uuid)
  }
}
const pwdLogin = async (captchaParams: any) => {
  uni.showLoading({ title: '登录中，请耐心等待...' })
  // loginForm.value.captchaVerification = captchaParams.captchaVerification;
  try {
    const success = await store.login(loginForm.value)
    if (success) {
      loginSuccess()
    }
  } finally {
    uni.hideLoading()
  }
}
const onCaptchaSuccess = async ({ code, uuid }) => {
  loginForm.value.code = code
  loginForm.value.uuid = uuid
  await pwdLogin({})
}
const loginSuccess = async () => {
  // await store.getUserInfo()
  uni.reLaunch({ url: '/pages/index/index' })
}
// 页面 onLoad 中处理租户
// onLoad(async (options) => {
//   console.log('options', options)
//   console.log('tenant', tenant);
//   console.log('tenantStore', tenantStore);

//   let tenantId: string | number = 7 // 默认 tenantId

//   // 如果是扫码进入，尝试从 scene 中解析 tenantId
//   if (options.scene) {
//     const sceneStr = decodeURIComponent(options.scene)
//     const sceneObj = parseScene(sceneStr)

//     if (sceneObj.tenantId) {
//       tenantId = sceneObj.tenantId
//       console.log('扫码获取 tenantId:', tenantId)
//     } else {
//       console.log('扫码参数中未包含 tenantId，使用默认值')
//     }
//   } else {
//     console.log('未扫码进入，使用默认 tenantId')
//   }

//   // 统一赋值与拉取租户信息
//   loginForm.value.tenantId = tenantId
//   await fetchTenantInfo(tenantId)
//   console.log('loginForm.value', loginForm.value)
// })
onLoad(async (options) => {
  tenantStore.loadFromStorage()
  const storedTenant = tenantStore.tenantInfo
  console.log('storedTenant', storedTenant)

  let tenantId = options?.scene
    ? parseScene(decodeURIComponent(options.scene))?.tenantId
    : options?.tenantId || storedTenant?.tenantId
  console.log('tenantId', tenantId)

  if (!storedTenant || storedTenant.tenantId !== tenantId) {
    console.log('进来了没')

    // 没缓存 或 tenantId 变了，重新请求
    await fetchTenantInfo(tenantId)
  }

  loginForm.value.tenantId = tenantId
})

function parseScene(scene: string): Record<string, string> {
  const obj: Record<string, string> = {}
  const params = decodeURIComponent(scene).split('&')
  for (const item of params) {
    const [key, value] = item.split('=')
    if (key) obj[key] = value
  }
  return obj
}
const fetchTenantInfo = async (tenantId: string | number) => {
  try {
    const res: any = await getTenantInfo(Number(tenantId))
    const data = res.data

    // 如果 logoUrl 是字符串形式的数组，需要转换
    if (typeof data.logoUrl === 'string') {
      try {
        const parsed = JSON.parse(data.logoUrl)
        if (Array.isArray(parsed)) {
          data.logoList = parsed // ✅ 新增一个字段存放数组
          data.logoUrl = parsed[1] // ✅ 默认显示第一张图
        }
      } catch (e) {
        console.warn('logoUrl 解析失败:', e)
        data.logoList = []
      }
    }
    console.log('返回的图片数据data', data)

    tenantStore.setTenant(data)
    console.log('tenant租户信息', tenant)
  } catch (e) {
    uni.showToast({ title: '租户信息加载失败', icon: 'none' })
  }
}
</script>

<style lang="scss">
.bg-wrapper {
  position: relative;
  width: 100%;
}

.bgImage,
.bgColor {
  width: 100%;
  display: block;
}

.bgColor {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  pointer-events: none; // ✅ 不拦截点击事件
}

.bgLogo {
  position: absolute;
  top: 18%;
  left: 6%;
  z-index: 2;
  width: 24%;
}

.bgTextZH {
  position: absolute;
  top: 42%;
  right: 5%;
  z-index: 2;
  font-size: 50rpx;
  font-weight: 600;
  color: #fff;
  letter-spacing: 2rpx;
}

.bgTextTibetan {
  position: absolute;
  top: 30%;
  right: 3%;
  z-index: 2;
  font-size: 48rpx;
  font-weight: 600;
  color: #fff;
}

.form-card {
  background-color: #fff;
  border-radius: 20rpx;
  margin: auto;
  width: 90%;
  height: 50%;
  padding: 20rpx 40rpx;
}

.form-border {
  overflow: hidden;
  /* 新增 */
  border: 2rpx solid #ccc;
  // margin: auto;
  /* 统一容器内边距 */
  border-radius: 50rpx;
  margin-top: 40rpx;
}

.form-register {
  margin-top: 40rpx;
  margin-left: 20rpx;
  font-size: 14px;

  text {
    color: red;
  }
}

.btn-wrapper {
  display: flex;
  justify-content: center; // ✅ 水平居中
}

.custom-shadow {
  width: 60vw;
  display: block;
}

.agreement {
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
}

.checkbox {
  transform: scale(0.8);
  margin-right: 8rpx;
  margin-bottom: 12rpx;
}

.agreement-text {
  font-size: 30rpx;
  color: #999;
}

.link {
  font-size: 30rpx;
  // color: #ad202f;
  color: #000;
  text-decoration: underline;
  margin: 0 8rpx;
}

.disabled {
  opacity: 0.6;
  background: #ccc;
}
</style>
